#==================================================
#	State Machine
#==================================================
#  子状态机
#==================================================
# @datetime: 2021-12-18 10:18:39
#==================================================
extends "State.gd"


signal state_changed(last_state_name, current_state_name)


var __nodes__ := {}

var _last_state : Node
var _current_state : Node



#==================================================
#   Set/Get
#==================================================
func get_current_state_name() -> String:
	return _current_state.name

func has_state(state_name: String) -> bool:
	return __nodes__.has(state_name)

func get_state(state_name: String) -> Node:
	return __nodes__[state_name]



#==================================================
#   自定义方法
#==================================================
#(override)
func _init_data():
	._init_data()
	if get_child_count() > 0:
		for child in get_children():
			__nodes__[child.name] = child
		switch_to(get_child(0).name)



#==================================================
#   状态方法
#==================================================
#(override)
func enter(data):
	# 此处写设置当前状态的逻辑
	# 设置哪个节点为当前执行的节点
	_current_state.enter(data)


#(override)
func exit():
	_current_state.exit()


#(override)
func state_process(arg0):
	# 此处写
	_current_state.state_process(arg0)


#(override)
func switch_to(state_name: String, data = null) -> bool:
	if has_state(state_name):
		# 如果存在有正在进行的 State，则停止
		if _current_state != null:
			# 开始停止当前状态
			_current_state.exit()
		
		# 开始启动切换的 State
		var state = get_state(state_name)
		if state != _last_state:
			_last_state = _current_state
			_current_state = state
			_current_state.enter(data)
			if _last_state:
				emit_signal("state_changed", _last_state.name, _current_state.name)
		return true
	else:
#		printerr("没有这个状态！", state_name)
		return false


##  切换到上一层的状态
## @state_name  State 名称
## @data=null  传入数据
func switch_to_upper_story(state_name: String, data = null) -> bool:
	return get_state_machine().switch_to(state_name, data)

